package com.namecard.namecardapi.util;

import com.namecard.namecardapi.entity.vo.EmailVO;
import com.namecard.namecardapi.entity.vo.SendVO;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * @author wzx
 */
public class PostEmailUtil {

    /**
     * 发送电子邮件不带附件
     */
    public static Boolean sendMail(SendVO sendVO , EmailVO emailVO){
        try {
            Transport.send(getMimeMessage(sendVO, emailVO));
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送电子邮件带附件
     */
    public static Boolean sendMailAndAttach(SendVO sendVO,EmailVO emailVO){
        MimeMessage message = getMimeMessage(sendVO, emailVO);
        MimeMultipart multipart = new MimeMultipart();
        //正文对象
        MimeBodyPart bodyPart = new MimeBodyPart();
        try {
            bodyPart.setContent(emailVO.getText(), emailVO.getTextEncoder());
            multipart.addBodyPart(bodyPart);
            //附件对象
            MimeBodyPart imagePart = new MimeBodyPart();
            imagePart.setFileName(emailVO.getAttachName());
            imagePart.setDataHandler(new DataHandler(new ByteArrayDataSource(new BufferedInputStream(Files.newInputStream(Paths.get(emailVO.getAttachUrl()))), "application/octet-stream")));
            multipart.addBodyPart(imagePart);
            message.setContent(multipart);
            Transport.send(message);
        } catch (MessagingException | IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private static MimeMessage getMimeMessage(SendVO sendVO, EmailVO emailVO) {
        try {
            // 连接到SMTP服务器587端口:
            Properties properties = new Properties();
            properties.put(EmailConstants.MAIL_SMTP_HOST, sendVO.getSmtp());
            //使用SMTPS协议端口
            properties.put(EmailConstants.MAIL_SMTP_PORT, EmailConstants.SMTP_PORT);
            //SMTPS协议
            properties.put(EmailConstants.SMTP_SOCKET_FACTORY_CLASS, EmailConstants.SSL_SOCKET_FACTORY);
            //启用用户认证
            properties.put(EmailConstants.MAIL_SMTP_AUTH, "true");
            //启用TLS加密
            properties.put(EmailConstants.MAIL_SMTP_STARTTLS_ENABLE, "true");
            // 获取Session实例:
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(sendVO.getUserName(), sendVO.getKey());
                }
            });
            session.setDebug(true);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sendVO.getUserName()));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(sendVO.getAccept()));
            message.setSubject(emailVO.getTitle(), emailVO.getTitleEncoder());
            // 邮件正文
            message.setText(emailVO.getText(), emailVO.getTextEncoder());
            return message;
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
